<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Protobuf WebSocket Test</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #messages { margin-top: 10px; }
    </style>
</head>
<body>
<h1>Protobuf WebSocket Test2</h1>
<input type="text" id="messageInput" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<br />
<div id="messages"></div>

<!-- 引入 Protobuf.js 库 -->
<script src="protobuf.min.js"></script>
<script>
    // 加载 fishshoot.proto 文件
    fetch('fishshoot.proto')
        .then(response => response.text())
        .then(protoDefinition => {
            // 使用 protobuf.parse 解析 proto 文件
            const root = protobuf.parse(protoDefinition).root;

            // 获取消息类型
            const FishShoot = root.lookupType('fishshoot');

            // 创建 WebSocket 连接
            const socket = new WebSocket("ws://localhost:7000/ws");
            socket.binaryType = "arraybuffer";

            // 连接打开时触发
            socket.onopen = function () {
                console.log("Connected to WebSocket server.");
            };

            // 接收消息时触发
            socket.onmessage = function (event) {
                const uint8Array = new Uint8Array(event.data);
                const message = FishShoot.decode(uint8Array);
                console.log('Received message:', message);
                document.getElementById("messages").innerHTML = message.content;
            };

            // 发送消息
            function sendMessage() {
                const message = FishShoot.create({
                    id: 1,
                    content: document.getElementById("messageInput").value
                });
                const buffer = FishShoot.encode(message).finish();
                socket.send(buffer);
                document.getElementById("messageInput").value = "";
            }

            // 连接关闭时触发
            socket.onclose = function (event) {
                console.log("WebSocket connection closed.", event);
            };

            // 发生错误时触发
            socket.onerror = function (error) {
                console.error("WebSocket error:", error);
            };

            // 将 sendMessage 函数绑定到全局对象
            window.sendMessage = sendMessage;
        })
        .catch(error => {
            console.error("Error loading proto file:", error);
        });
</script>
</body>
</html>